﻿package game.socket {
	import game.objects.GameObject;
	import flash.utils.ByteArray;
	
	public class Sockets extends GameObject {
		
		public static const POLICY:int		= 0;
		public static const LOGIN:int		= 1;
		public static const SHOP:int		= 2;
		
		private var policy:SocketPolicy = new SocketPolicy;
		private var connections:Vector.<SocketConnection> = new Vector.<SocketConnection>;
		
		public function Sockets():void {
			
			var socket:SocketConnection;
			for each (var obj:SocketObject in config.sockets) {
				socket = new SocketConnection ( obj );
				configurationSocket(socket);
				connections.push( socket );
			}
			
			policy.addEventListener(SocketEvent.POLICY,		function (event:SocketEvent)	{ dispatchEvent ( new SocketEvent ( event.type, event.socket ) ); });
			policy.addEventListener(SocketEvent.ERROR,		function (event:SocketEvent)	{ dispatchEvent ( new SocketEvent ( event.type, event.socket ) ); });
			
		}
		
		public function getPolicy():void {
			policy.check(config.policy);
		}
		
		public function configurationSocket(socket:SocketConnection):void {
			socket.addEventListener(SocketHandler.RECIVE,		function (event:SocketHandler)	{ dispatchEvent ( new SocketHandler ( event.type, event.socketPackage ) ); });
			socket.addEventListener(SocketEvent.CONNECTED,		function (event:SocketEvent)	{ dispatchEvent ( new SocketEvent ( event.type, event.socket ) ); });
			socket.addEventListener(SocketEvent.DISCONNECTED,	function (event:SocketEvent)	{ dispatchEvent ( new SocketEvent ( event.type, event.socket ) ); });
			socket.addEventListener(SocketEvent.ERROR,			function (event:SocketEvent)	{ dispatchEvent ( new SocketEvent ( event.type, event.socket ) ); });
		}
		
		public function send(server:int, ba:ByteArray):void {
			var index:int = getSocketIndex(server); 
			if (index==-1) return;
			
			var socket:SocketConnection = connections[index] as SocketConnection;
			if (!socket) return;
			
			socket.send ( ba );
		}
		
		private function getSocketIndex(server:int):int {
			var index:int = -1;
			for (var i in connections) {
				if (connections[i].data.type == server) {
					index = i;
					break;
				}
			}
			return index;
		}
		
	}
	
}